#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/12/5 13:50
# @Author  : Andrewq
# @Site    : nope
# @File    : NewspaperInfoModel.py
# @Software: PyCharm
import datetime

from flask import current_app
from sqlalchemy import and_
from .. import db
from .models import NewspaperInfo
from ..utils import commons
from ..utils.response_code import RET


class NewspaperInfoManager(NewspaperInfo):
    @classmethod
    def get_order_info_by_tags(cls, **kwargs):
        tag_name = kwargs.get('tag')
        keyword = kwargs.get('keyword')

        filter_list = []
        if tag_name == "报刊ID":
            filter_list.append(cls.NewspaperID.contains(keyword))
        elif tag_name == "报刊名":
            filter_list.append(cls.NewspaperName.like('%'+keyword+'%'))
        elif tag_name == "报刊价格":
            filter_list.append(and_(cls.Price >= float(keyword.split(",")[0]), cls.Price <= float(keyword.split(",")[1])))

        try:
            result_list = db.session.query(cls.NewspaperID,
                                           cls.NewspaperName,
                                           cls.OtherInfo,
                                           cls.Price,
                                           cls.CreateTime
                                           ).filter(*filter_list)
        except Exception as e:
            return {"code": RET.DBERR, "message": "查询出错", "error": str(e)}

        if not result_list.first():
            return {"code": RET.OK, "message": "暂无数据", "data": []}

        return {"code": RET.OK, "message": "查询成功！", "data": commons.query_to_dict(result_list.all())}

    @classmethod
    def get_newspaper_all_info(cls):
        filter_list = []

        try:

            newspapers = db.session.query(cls).filter(*filter_list)

        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，获取信息失败', 'error': str(e)}

        if not newspapers.first():
            return {'code': RET.NODATA, 'message': '没有员工数据'}

        back_data = commons.query_to_dict(newspapers.all())

        return {'code': RET.OK, 'message': '查询用户信息成功', 'data': back_data}

    @classmethod
    def add_newspaper_info(cls, **kwargs):

        filter_list = []
        filter_list.append(cls.NewspaperName == kwargs.get('NewspaperName'))

        try:
            newspaper = db.session.query(cls).filter(*filter_list)

            if newspaper.first():
                return {'code': RET.DATAEXIST, 'message': '报刊存在'}

            newspaper_ID = (datetime.datetime.now()).strftime('%Y%m%d%H%M%S')

            Newspaper = NewspaperInfo(
                NewspaperID=newspaper_ID,
                NewspaperName=kwargs.get('NewspaperName'),
                Price=kwargs.get('Price'),
                OtherInfo=kwargs.get('OtherInfo'),
            )

            db.session.add(Newspaper)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，获取信息失败', 'error': str(e)}

        data = commons.query_to_dict(Newspaper)

        return {'code': RET.OK, 'message': '添加数据成功', 'data': data}

    @classmethod
    def delete_newspaper_info_list(cls, **kwargs):
        data = kwargs.get('data')

        try:
            for dt in data:
                filter_list = []
                filter_list.append(cls.NewspaperID == dt['data']['NewspaperID'])

                newspaper = db.session.query(cls).filter(*filter_list)

                if not newspaper.first():
                    continue

                newspaper.delete()
                db.session.commit()

        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，获取信息失败', 'error': str(e)}

        return {'code': RET.OK, 'message': '成功删除数据', 'data': data}

    @classmethod
    def edit_newspaper_info(cls, **kwargs):
        filter_list = []

        try:
            filter_list.append(cls.NewspaperID == kwargs.get('NewspaperID'))

            newspaper = db.session.query(cls).filter(*filter_list)

            if not newspaper.first():
                return {'code': RET.NODATA, 'message': '没有该报刊数据'}

            newspaper.update({'NewspaperName': kwargs.get('NewspaperName'),
                              'Price': kwargs.get('Price'),
                              'OtherInfo': kwargs.get('OtherInfo')})
            db.session.commit()

        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，获取信息失败', 'error': str(e)}

        return {'code': RET.OK, 'message': '修改信息成功', 'data': kwargs}

    @classmethod
    def delete_newspaper_info(cls, **kwargs):
        filter_list = []

        filter_list.append(cls.NewspaperID == kwargs.get('NewspaperID'))

        try:
            newspaper = db.session.query(cls).filter(*filter_list)

            if not newspaper.first():
                return {'code': RET.NODATA, 'message': '没有用户数据'}

            newspaper.delete()
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，获取信息失败', 'error': str(e)}

        back_data = {
            'NewspaperID': kwargs.get('NewspaperID'),
        }

        return {'code': RET.OK, 'message': '删除用户数据成功', 'data': back_data}